import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: newCachedThreadPool  创建一个可缓存的线程池。如果线程池的大小超过了处理任务所需要的线程，
 * 那么就会回收部分空闲（60秒不执行任务）的线程，当任务数增加时，此线程池又可以智能的添加新线程来处理任务。
 * 此线程池不会对线程池大小做限制，线程池大小完全依赖于操作系统（或者说JVM）能够创建的最大线程大小。
 * @author: zys
 * @create: 2020-10-12 13:03
 **/
public class CachedThreadPool {

    public static void main(String[] args) {
        System.out.println("欢迎来到线程世界!");

        //创建一个可重用固定线程数的线程池
        ExecutorService pool = Executors.newCachedThreadPool();
        //创建实现了Runnable接口对象，Thread对象当然也实现了Runnable接口
        CachedThreadPool.MyThread t1 = new CachedThreadPool().new MyThread("线程实例1");
        CachedThreadPool.MyThread t2 = new CachedThreadPool().new MyThread("线程实例2");
        CachedThreadPool.MyThread t3 = new CachedThreadPool().new MyThread("线程实例3");
        CachedThreadPool.MyThread t4 = new CachedThreadPool().new MyThread("线程实例4");
        //将线程放入池中进行执行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        //关闭线程池
        pool.shutdown();
    }

    class MyThread extends Thread {
        public MyThread() {
        }

        public MyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            System.out.println(this.getName() + "正在执行。。。");
            System.out.println(Thread.currentThread().getName() + "正在执行。。。");
        }
    }
}
